<template>
  <div class="user-add-container">
    <el-card>
      <div class="page-title">
        <el-page-header @back="goBack" content="添加新用户"></el-page-header>
      </div>

      <div class="form-container">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-document"></i>
              基本信息
            </div>

            <el-form-item label="用户编码" prop="userCode">
              <el-input v-model="form.userCode" placeholder="请输入用户编码"></el-input>
            </el-form-item>

            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称"></el-input>
            </el-form-item>

            <el-form-item label="用户角色" prop="roleId">
              <el-select v-model="form.roleId" placeholder="请选择用户角色" style="width:100%">
                <el-option
                    v-for="role in roles"
                    :key="role.id"
                    :label="role.roleName"
                    :value="role.id">
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>{{ role.roleName }}</span>
                    <span style="color: #8492a6; font-size: 13px">{{ role.roleCode }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="用户状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="2">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-lock"></i>
              安全信息
            </div>

            <el-form-item label="密码" prop="password">
              <el-input
                  type="password"
                  v-model="form.password"
                  placeholder="请输入密码"
                  show-password
              ></el-input>
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                  type="password"
                  v-model="form.confirmPassword"
                  placeholder="请再次输入密码"
                  show-password
              ></el-input>
            </el-form-item>

            <div class="password-info">
              <i class="el-icon-info"></i>
              系统将对用户密码进行加密加盐处理，确保密码安全存储
            </div>
          </div>

          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-user"></i>
              个人信息
            </div>

            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                  v-model="form.birthday"
                  type="date"
                  placeholder="选择出生日期"
                  style="width:100%"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码"></el-input>
            </el-form-item>

            <el-form-item label="联系地址" prop="address">
              <el-input
                  type="textarea"
                  v-model="form.address"
                  placeholder="请输入联系地址"
                  :rows="3"
              ></el-input>
            </el-form-item>
          </div>

          <div class="form-footer">
            <el-button type="primary" @click="submitForm" :loading="loading">提交用户信息</el-button>
            <el-button @click="resetForm">重置表单</el-button>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request' // 确保路径正确

export default {
  name: 'UserAdd',
  setup() {
    const router = useRouter()
    const formRef = ref(null)
    const loading = ref(false)

    const form = reactive({
      userCode: '',
      userName: '',
      password: '',
      confirmPassword: '',
      roleId: '',
      status: 1,
      gender: 1,
      birthday: '',
      phone: '',
      address: ''
    })

    const roles = ref([
      { id: 1, roleName: '系统管理员', roleCode: 'admin' },
      { id: 2, roleName: '普通员工', roleCode: 'user' },
      { id: 3, roleName: '经理', roleCode: 'manager' }
    ])

    const validatePassword = (rule, value, callback) => {
      if (value !== form.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    const rules = reactive({
      userCode: [
        { required: true, message: '请输入用户编码', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      userName: [
        { required: true, message: '请输入用户名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: validatePassword, trigger: 'blur' }
      ],
      roleId: [
        { required: true, message: '请选择用户角色', trigger: 'change' }
      ],
      phone: [
        { pattern: /^1[0-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ]
    })

    const submitForm = () => {
      formRef.value.validate(valid => {
        if (!valid) {
          ElMessage.warning('请填写完整的表单信息')
          return
        }

        ElMessageBox.confirm('确定要添加新用户吗？', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          loading.value = true

          // 准备提交数据，处理字段名映射
          const submitData = {
            userCode: form.userCode,
            userName: form.userName,
            userPassword: form.password, // 前端的password映射到后端的userPassword
            userRole: form.roleId, // 前端的roleId映射到后端的userRole
            status: form.status,
            gender: form.gender,
            birthday: form.birthday,
            phone: form.phone,
            address: form.address
          }

          // 使用request进行POST请求
          request.post('/user', submitData)
              .then(response => {
                if (response.data.flag) {
                  ElMessage.success('用户添加成功！')
                  router.push('/homepage/userList') // 跳转到用户列表页面
                } else {
                  ElMessage.error(response.data.message || '添加失败')
                }
              })
              .catch(error => {
                console.error('添加用户错误:', error)
                ElMessage.error(error.response?.data?.message || '添加用户失败')
              })
              .finally(() => {
                loading.value = false
              })
        }).catch(() => {
          // 取消操作
        })
      })
    }

    const resetForm = () => {
      formRef.value.resetFields()
      form.status = 1
      form.gender = 1
    }

    const goBack = () => {
      router.push("/homepage")
    }

    return {
      formRef,
      form,
      roles,
      rules,
      loading,
      submitForm,
      resetForm,
      goBack
    }
  }
}
</script>

<style scoped>
.user-add-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
}

.form-container {
  padding: 20px;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.section-title {
  font-size: 16px;
  color: #409EFF;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.password-info {
  background: #f0f8ff;
  border-left: 4px solid #4a9cff;
  padding: 15px;
  border-radius: 4px;
  margin-top: 15px;
  font-size: 14px;
  color: #555;
}

.password-info i {
  color: #4a9cff;
  margin-right: 8px;
}

.form-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}
</style>